package com.jrx.anytxn.reporting.job.xib.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.customer.constant.BankCardConstant;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.entity.CmCustomerAddressInfo;
import com.jrx.anytxn.customer.entity.CmCustomerContactInfo;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerAddressInfoMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerBankcardInfoMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerContactInfoMapper;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.param.entity.PrCodeTable;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.ICodeTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.entity.CmInteCoCustInfo;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanAccountInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @comment: 零售客户信息数据报表Processor
 * @author: hsoong
 * @date: 2021/7/1 09:51
 */
@Service
public class CustInfoReportingProcesser implements ItemProcessor<CmCustomerFirstLevel, CmInteCoCustInfo> {

    private static Logger logger = LoggerFactory.getLogger(CustInfoReportingProcesser.class);

    @Resource
    ExtCmCustomerContactInfoMapper extCmCustomerContactInfoMapper;

    @Resource
    ExtCmCustomerAddressInfoMapper extCmCustomerAddressInfoMapper;

    @Resource
    ExtAmLoanAccountInfoMapper extAmLoanAccountInfoMapper;

    @Resource
    ExtCmCustomerBankcardInfoMapper extCmCustomerBankcardInfoMapper;

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Autowired
    ICustomerService iCustomerService;

    @Autowired
    private ICodeTableService codeTableService;

    @Override
    public CmInteCoCustInfo process(CmCustomerFirstLevel cust) throws Exception {
        logger.info("正在处理一级客户编号为: {}的记录...", cust.getCustomerId());


        try {
            if (cust == null) { return null; }

            if (StringUtils.isEmpty(cust.getEcifId())) {
                return null;
            }

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);

            String todayStr = DateUtils.format(org.getToday(), "yyyy-MM-dd");
            final Date today = DateUtils.parseDate(todayStr, "yyyy-MM-dd");

            final CmInteCoCustInfo cicci = new CmInteCoCustInfo();
            cicci.setTenantId(cust.getTenantId());

            //数据日期
            cicci.setEtlDt(today);
            //法人机构标识
            cicci.setLpOrgNo("XIB");
            //核心客户编号
            cicci.setCoreCustNo(cust.getEcifId());
            //证件类型代码
            cicci.setCertTypeCd(cust.getIdType());
            //证件号码
            cicci.setCertNo(cust.getIdNumber());
            //性别代码
            cicci.setGenderCd(changeGenderCode(cust.getSex()));
            //出生日期
            cicci.setBirthDt(cust.getBirthDate());
            //性别
            cicci.setEthnicCd(cust.getRace());
            //农户标志
            cicci.setFarmerFlg("");
            //国籍代码
            cicci.setNationCd(StringUtils.defaultIfEmpty(cust.getNationality(), "CN"));
            //行政区域
            cicci.setDistCd(cust.getIdNumber().substring(0, 6));
            //证件签发机构
            cicci.setIssueCertOrg(cust.getIdIssueAgent());

            //二级客户表相关信息
            Optional<CmCustomerSecondLevel> optSecond = iCustomerService.getSecondByCustomerIdAndTensnId(cust.getCustomerId(), cust.getTenantId())
                    .stream()
                    .findFirst();

            if (optSecond.isPresent()) {
                CmCustomerSecondLevel second = optSecond.get();

                //手机号码
                cicci.setMobileNo(second.getMobile());
                //电子邮箱
                cicci.setEmail("");

                //银行卡片信息
                extCmCustomerBankcardInfoMapper.selectByChannelCusId(cust.getCustomerId(), second.getChannel(), BankCardConstant.STATUS_BANKCARD_1, cust.getTenantId())
                        .stream()
                        .filter(x -> "1".equals(x.getCardType()))
                        .findFirst()
                        .ifPresent(x -> {
                            //银行卡号(默认收款卡号)
                            cicci.setBankCardNo(x.getCardNumber());
                            //银行卡开户行
                            cicci.setBankCardOpenBank(x.getBankName());
                        });

                //婚姻状态
                cicci.setMarriageStatusCd(second.getMaritalStatus());
                //学历代码
                cicci.setEduDegreeCd(second.getEducation());
                //学位代码，999-其他
                cicci.setDegreeCd("999");
                //住宅电话
                cicci.setHomeTelNum(second.getHomePhone());
                //行业代码
                //职业代码
                cicci.setCareerCd(second.getOccuptionType());
                //职务代码
                cicci.setPosCd("");
                //职称代码
                cicci.setTitleCd("");

                if (StringUtils.isNotBlank(cust.getIdEffectiveDate())) {
                    cicci.setIdCardEffectDt(DateUtils.parseDate(cust.getIdEffectiveDate(), "yyyy-MM-dd"));
                }

                if (StringUtils.isNotBlank(cust.getIdExpireDate())) {
                    cicci.setIdCardInvalidDt(DateUtils.parseDate(cust.getIdExpireDate(), "yyyy-MM-dd"));
                }

                //获取联系人表信息
                CmCustomerContactInfo cond = new CmCustomerContactInfo();
                cond.setChannel(second.getChannel());
                cond.setCustomerId(second.getCustomerId());
                cond.setContactStatus(CustomerConstant.STATUS_NORMAL);
                cond.setTenantId(second.getTenantId());
                Optional<CmCustomerContactInfo> optContact = extCmCustomerContactInfoMapper.selectByCondSelective(cond)
                        .stream()
                        .findFirst();
                if (optContact.isPresent()) {
                    CmCustomerContactInfo contact = optContact.get();
                    //联系人名称
                    cicci.setLinkmanName(contact.getChineseName());
                    //联系人代码
                    cicci.setLinkmanRelaCd(contact.getRelationship());
                    //联系人电话
                    cicci.setLinkmanTel(contact.getMobile());
                }

                //工作单位名称
                cicci.setCorpName(second.getCompanyName());
                //工作单位性质
                cicci.setCorpType(second.getCompanyAttribute());
                //工作单位地址
                cicci.setCorpAddr("");

                //联系地址表信息
                List<CmCustomerAddressInfo> addresses = extCmCustomerAddressInfoMapper.selectByCustomerIdAndTenantId(second.getCustomerId(), second.getTenantId());
                for (CmCustomerAddressInfo ccai : addresses) {
                    String address = "";
                    if(!com.jrx.anytxn.common.uitl.StringUtils.isBlank(ccai.getProvince())){
                        PrCodeTable province = codeTableService.findByTypeAndCodeId(ReportingConstant.PROVINCE_TYPE_ID, ccai.getProvince(), ccai.getTenantId());
                        if(null != province){
                            address = address + province.getCodeName();
                        }
                    }
                    if(!com.jrx.anytxn.common.uitl.StringUtils.isBlank(ccai.getCity())){
                        PrCodeTable city = codeTableService.findByTypeAndCodeId(ReportingConstant.CITY_TYPE_ID, ccai.getCity(),ccai.getTenantId());
                        if(null != city){
                            address = address + city.getCodeName();
                        }
                    }
                    if(!com.jrx.anytxn.common.uitl.StringUtils.isBlank(ccai.getDistrict())){
                        PrCodeTable area = codeTableService.findByTypeAndCodeId(ReportingConstant.AREA_TYPE_ID, ccai.getDistrict(),ccai.getTenantId());
                        if(null != area){
                            address = address + area.getCodeName();
                        }
                    }
                    address = address + ccai.getAddress();

                    switch (ccai.getAddressType()) {
                        case "3":
                            //单位地址
                            cicci.setCorpAddr(address);
                            cicci.setCorpAddrZipCd(ccai.getZipcode());
                            break;
                        case "0":
                            //户籍地址
                            cicci.setFamilyAddr(address);
                            cicci.setIdCardAddr(ccai.getAddress());
                            break;
                        case "1":
                            //家庭地址
                            cicci.setResdntAddr(address);
                            cicci.setResdntAddrZipCd(ccai.getZipcode());
                            break;
                        case "2":
                            //通讯地址
                            cicci.setPostaAddrZipCd(ccai.getZipcode());
                            break;
                        default:
                            break;
                    }
                }

                //客户经理编号
                cicci.setCustMgrNo(second.getBankMgrNo());
                //所属机构编号
                cicci.setBelongOrgNo(second.getBankOrgNo());
                //考核机构编号
                cicci.setAssesOrgNo(second.getBankOrgNo());
            }

            //月收入,年收入,月收入等级, 十级分类(暂不设置)
            //来源平台编号
            cicci.setSrcPlatNo("CCS");
            //更新标记, 0-新增
            cicci.setUpdateFig("0");
            //客户类型代码, 40-自然人
            cicci.setCustTypeCd("40");

            //年龄
            String birthYear = DateUtils.format(cust.getBirthDate(), "yyyy");
            String thisYear = DateUtils.format(new Date(), "yyyy");
            int years = Integer.parseInt(thisYear) - Integer.parseInt(birthYear);
            cicci.setAge(BigDecimal.valueOf(years));

            //txn客户编号
            cicci.setCustNo(cust.getCustomerId());
            //客户名称
            cicci.setCustName(cust.getChineseName());
            //居住城市编码
            cicci.setResdntCitCd("");
            // 客户申请日期
            cicci.setCustAppDt(cust.getCreateTime());

            return cicci;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("xibCustInfoReportingJob出错了：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 改变性别码值
     * @param genderCode
     * @return
     */
    public static String changeGenderCode(String genderCode) {
        //  1、男性 2、女性 0、未知
        String gender = "0";
        if (StringUtils.isNotBlank(genderCode)) {
            // 我们的码值 0-男 1-女
            if ("0".equals(genderCode)) {
                gender = "1";
            }else if ("1".equals(genderCode)) {
                gender = "2";
            }
        }
        return gender;
    }
}
